package com.kejizhentan.controller;

import com.kejizhentan.service.IUserService;
import com.kejizhetan.bean.Role;
import com.kejizhetan.bean.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private IUserService userInforService;
    /**
     * @descrition：查询所有用户信息
     * @param: null
     * @auther: kejizhentan
     * @date: 2022/3/6 11:17
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfos = userInforService.findAll();
        mv.addObject("userList",userInfos);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     * @descrition： 新增用户
     * @auther: kejizhentan
     * @date: 2022/3/6 12:07
     */
    @RequestMapping("/save.do")
    public String saveUser(UserInfo userInfo) throws Exception{
        userInforService.save(userInfo);
        return "redirect:findAll.do";
    }

    /**
     * @descrition：查询用户详情
     * @auther: kejizhentan
     * @date: 2022/3/6 12:09
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) throws Exception {
        UserInfo userInfo =  userInforService.findById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    /**
     * @descrition：查询用户以及用户可以添加的角色
     * @auther: kejizhentan
     * @date: 2022/3/6 15:27
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) throws Exception {
        ModelAndView mv = new ModelAndView();
        //1.根据用户id查询用户
        UserInfo userInfo = userInforService.findById(userid);
        //2.根据用户id查询可以添加的角色
        List<Role> otherRoles = userInforService.findOtherRoles(userid);
        mv.addObject("user", userInfo);
        mv.addObject("roleList", otherRoles);
        mv.setViewName("user-role-add");
        return mv;
    }

    /**
     * @descrition：给用户添加角色
     * @auther: kejizhentan
     * @date: 2022/3/6 15:42
     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception {
        userInforService.addRoleToUser(userId, roleIds);
        return "redirect:findAll.do";
    }
}
